/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.web.wx;

import net.guerlab.smart.pay.core.exception.WxPayConfigInvalidException;
import net.guerlab.smart.pay.service.entity.WxPayConfig;
import net.guerlab.smart.pay.service.properties.PayProperties;
import net.guerlab.smart.pay.service.service.WxPayConfigService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 抽象微信支付控制器
 *
 * @author guer
 */
public abstract class AbstractWxPayController {

    /**
     * 应用ID关键字
     */
    protected static final String KEY_APP_ID = "appId";

    protected WxPayConfigService configService;

    protected PayProperties payProperties;

    /**
     * 获取支付渠道名称
     *
     * @return 支付渠道名称
     */
    final String getPayChannel() {
        return "WX_" + getWxPayServiceType().name();
    }

    /**
     * 获取微信支付服务类型
     *
     * @return 微信支付服务类型
     */
    protected abstract WxPayServiceType getWxPayServiceType();

    /**
     * 构造微信支付服务
     *
     * @param appId
     *         应用ID
     * @return 微信支付服务
     */
    protected WxPayService buildWxPayService(String appId) {
        return buildWxPayService(appId, false);
    }

    /**
     * 构造微信支付服务
     *
     * @param appId
     *         应用ID
     * @param checkEnable
     *         检查是否启用
     * @return 微信支付服务
     */
    protected WxPayService buildWxPayService(String appId, boolean checkEnable) {
        WxPayConfig config = configService.selectByIdOptional(appId).orElseThrow(WxPayConfigInvalidException::new);

        if (checkEnable && !config.getEnable()) {
            throw new WxPayConfigInvalidException();
        }

        return new WxPayService(payProperties, config);
    }

    @Autowired
    public void setConfigService(WxPayConfigService configService) {
        this.configService = configService;
    }

    @Autowired
    public void setPayProperties(PayProperties payProperties) {
        this.payProperties = payProperties;
    }
}
